import React, { useEffect, useMemo, useState } from 'react';
import { /* Spin, */ Tooltip } from 'antd';

import StepList from '@/pages/SalaryManage/components/StepList';
import CheckHeader from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckHeader';
import CheckBody from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/CheckBody';

import BaseSettingProvider from '@/pages/SalaryManage/components/BaseSettingProvider';
import { ColumnProcessor, CommonColumnInterceptor } from '@/pages/SalaryManage/SalaryCalculate/Recheck/ColumnProcessor';
import {
    summaryFieldChooser,
    numberFilter,
    orFilter
} from '@/pages/SalaryManage/SalaryCalculate/Recheck/SummaryProcessor';
import OperateCell from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/OperateRender';
import RejectModal from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/RejectModal';
import PayrollModal from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/PayrollModal';
import ArticleWagesModal from '@/pages/SalaryManage/SalaryCalculate/Recheck/components/ArticleWagesModal';
import styles from '@/pages/SalaryManage/SalaryCalculate/Recheck/index.less';
import { CHECK_STATUS } from '@/pages/SalaryManage/constant/recheckConstant';
import { wrapRecheckDetail } from '@/pages/SalaryManage/utils/pageWrapUtil';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

const EMPTY_OBJECT = {};
const RecheckSummaryChooser = summaryFieldChooser(
    orFilter(numberFilter, col => ({
        success: col.dataIndex === 'employeeName',
        result: { [col.dataIndex]: '合计' }
    }))
);
const Recheck = wrapRecheckDetail(props => {
    const {
        sharePeriod,
        shareOrganizationCode,
        period,
        searchModel,
        checkButtonList,
        selectedRows,
        rowKey,
        tableHeader,
        columnProcessor,
        modalVisible,
        currentRecord,
        payrollModalVisible,
        articleWagesVisible,
        articleWagesPower,
        articleWagesMsg,
        summaryFields = RecheckSummaryChooser,
        pagination,
        dispatch,
        dispatchType,
        dataSource = [],
        tableLoading,
        stepLoading,
        tableProps = EMPTY_OBJECT
    } = props;

    const [organizationTreeData, setOrganizationTreeData] = useState({});

    useEffect(() => {
        const resetInit = async () => {
            dispatch({
                type: dispatchType.reset,
                payload: {
                    organizationCode: shareOrganizationCode
                }
            });

            const {
                organizationResponse: response,
                defaultOrganizationCode: defaultSelectCode
            } = await fetchOrganizationListAndDefault(shareOrganizationCode);
            setOrganizationTreeData(response);
            if (shareOrganizationCode !== defaultSelectCode) {
                dispatch({
                    type: dispatchType.sharedState,
                    payload: {
                        shareOrganizationCode: defaultSelectCode,
                        sharePeriod: undefined
                    }
                })
                dispatch({
                    type: dispatchType.reset,
                    payload: {
                        organizationCode: defaultSelectCode
                    }
                });
            }
        };
        resetInit().then(() => {
            dispatch({
                type: dispatchType.initType,
                payload: sharePeriod
            });
        });
    }, []);

    const memoDataSource = useMemo(
        () =>
            []
                .concat(dataSource)
                .map(item => ({ ...item.dynamicEmployeeInfo, ...item.dynamicSalaryPayrollInfo, ...item })),
        [dataSource]
    );

    return (
        <div className={salaryStyle.salaryWrapper}>
            {/* <Spin spinning={loading.global && !tableLoading}> */}
            <StepList
                period={period}
                loading={stepLoading}
                organizationCode={searchModel?.organizationCode}
            />
            <CheckHeader
                selectedRows={selectedRows}
                period={period}
                dispatch={dispatch}
                dispatchType={dispatchType}
                checkButtonList={checkButtonList}
                searchModel={searchModel}
                organizationList={organizationTreeData}
            />
            <BaseSettingProvider organizationCode={searchModel?.organizationCode}>
                <CheckBody
                    rowKey={rowKey}
                    tableHeader={tableHeader}
                    columnProcessor={columnProcessor}
                    summaryFields={summaryFields}
                    dataSource={memoDataSource}
                    pagination={pagination}
                    dispatch={dispatch}
                    searchModel={searchModel}
                    dispatchType={dispatchType}
                    tableLoading={tableLoading}
                    tableProps={tableProps}
                    selectedRows={selectedRows}
                    />
            </BaseSettingProvider>
            <RejectModal
                dispatchType={dispatchType}
                dispatch={dispatch}
                modalVisible={modalVisible}
                currentRecord={currentRecord}
                period={period}
            />
            <PayrollModal
                period={period}
                dispatchType={dispatchType}
                dispatch={dispatch}
                organizationCode={searchModel?.organizationCode}
                visible={payrollModalVisible}
            />
            <ArticleWagesModal
                dispatchType={dispatchType}
                dispatch={dispatch}
                msg={articleWagesMsg}
                modalVisible={articleWagesVisible}
                power={articleWagesPower}
            />
            {/* </Spin> */}
        </div>
    );
});

const RejectTooltip = ({ createUser, createTime, remark }) => (
    <>
        <div>备注人：{createUser}</div>
        <div>备注时间：{createTime}</div>
        <div>驳回备注：{remark}</div>
    </>
);

const RecheckColumnProcessor = dispatchType =>
    new ColumnProcessor(
        {
            id: {
                hidden: true,
                fixed: true
            },
            employeeName: {
                fixed: true,
                width: 120,
                render: (text, record) => record.generateStatus === 0 ? (
                    <span style={{ color: '#f5222d' }}>
                        {text}
                        <Tooltip title={record.generateError}>
                            <i className="icon iconfont iconjinggao" style={{
                                color: '#f5222d',
                                fontSize: 16,
                                marginLeft: 5,
                                verticalAlign: 'top'
                            }}></i>
                        </Tooltip>
                    </span>
                ) : text
            },
            employeeNo: {
                fixed: true,
                width: 100
            },
            totalPayAmtRate: {
                scale: true,
                width: 170
            },
            hrCheckStatusName: {
                className: styles.pStatusCell,
                render(text, record) {
                    return (
                        <>
                            {
                                record.hrCheckStatus === CHECK_STATUS.REJECT.code ||
                                record.hrCheckStatus === CHECK_STATUS.FINAL_REJECT.code
                                    ? (
                                        <Tooltip
                                            title={<RejectTooltip {...record.hrPayrollRejectResultVo} />}
                                            placement="bottomLeft"
                                        >
                                            <i className="p-status-icon-reject" />
                                        </Tooltip>
                                    )
                                    : null
                            }
                            <div>{text}</div>
                        </>
                    );
                }
            },
            financeCheckStatusName: {
                className: styles.pStatusCell,
                render(text, record) {
                    return (
                        <>
                            {record.financeCheckStatus === CHECK_STATUS.REJECT.code ? (
                                <Tooltip
                                    title={<RejectTooltip {...record.financePayrollRejectResultVo} />}
                                    placement="bottomLeft"
                                >
                                    <i className="p-status-icon-reject" />
                                </Tooltip>
                            ) : null}
                            <div>{text}</div>
                        </>
                    );
                }
            }
        },
        CommonColumnInterceptor,
        null,
        [],
        [
            {
                title: '操作',
                dataIndex: '_operate',
                fixed: 'right',
                width: 150,
                align: 'center',
                render(text, record /* , i */) {
                    return <OperateCell text={text} record={record} dispatchType={dispatchType} />;
                }
            }
        ]
    );

export { RecheckColumnProcessor, Recheck };
